package controls {
	import com.adobe.serialization.json.JSON;
	
	import events.RandomEvent;
	
	import flare.vis.controls.Control;
	import flare.vis.data.Data;
	import flare.vis.data.NodeSprite;
	
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import org.osmf.events.TimeEvent;
	
	public class RandomEventControl extends Control {
		public var timer:Timer;
		public var queue:Array = [];
		public var data:Data;
		public var idRange:Array = [0, 20];
		public var numberOfEvents:int = 20;
		private var _cur:NodeSprite;
		public function RandomEventControl(toggle:Function=null) {
			super();
			generateEvents();
			trace('RandomEventControl >', JSON.encode(queue));
			timer = new Timer(2000, queue.length + 1);
			timer.addEventListener(TimerEvent.TIMER, function(event:Event):void {
				trace('RandomEventControl Timer.');
				if (queue.length > 0) {
					var obj:Object = queue.pop();
					trace('RandomEventControl >', JSON.encode(obj));
					trace('RandomEventControl >', data);
					for each (var node:NodeSprite in data.nodes) {
						if (node.data.id == obj.id) {
							_cur = node;
							fireEvent(RandomEvent.TOGGLE_STATUS);
						}
					}
//					timer.reset();
					timer.delay = obj.delay;
//					timer.start();
				}
//				timer.start();
			});
			timer.start();
			if (toggle != null) this.addEventListener(RandomEvent.TOGGLE_STATUS, toggle);
		}
		/** @private */
		protected function fireEvent(type:String):void
		{
			if (hasEventListener(type)) {
				dispatchEvent(new RandomEvent(RandomEvent.TOGGLE_STATUS, _cur, _cur.data.online, !_cur.data.online));
			}
		}
		
		private function generateEvents():void {
			queue = [];
			for (var i:int = 0; i < numberOfEvents; ++i) {
				var o:Object = {};
				o.delay = int((Math.random() * 5)*1000 + 1000);
				o.type = RandomEvent.TOGGLE_STATUS;
				o.id = int(Math.random() * 20) + 1;
				queue.push(o);
			}
		}
	}
	
}
